/*
 * ContentFetcher.java
 *
 * Created on May 7, 2007, 1:33 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.semanticvoid.lifelogger.http;

import com.semanticvoid.lifelogger.configuration.ConfigManager;
import com.semanticvoid.lifelogger.configuration.Constants;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Class for fetching the contents over http.
 * @author anand kishore
 */
public class ContentFetcher {
    
    /**
     * The config manager instance
     */
    static ConfigManager conMgr = ConfigManager.getInstance();
    
    /**
     * Fecth the contents of the given URL
     * @param httpURL the URL
     * @return the html/text contents of the URL
     * null on error
     */
    public static String fetch(String httpURL) {
        // return null if the URL is null or blank
        if(httpURL == null || httpURL.equals("")) {
            return null;
        }
        
        // The content buffer
        StringBuffer content = null;
        BufferedReader rdr = null;
        
        // Set proxy variables
        if(conMgr.isProxy()) {
            System.getProperties().put("proxySet", "true");
            System.getProperties().put("proxyHost", conMgr.getValueForKey(Constants.KEY_FOR_PROXY_URL));
            System.getProperties().put("proxyPort", conMgr.getValueForKey(Constants.KEY_FOR_PROXY_PORT));
            // @todo add support for proxy authentication
        }
        
        try {
            URL url = new URL(httpURL);
            URLConnection con = url.openConnection();
            HttpURLConnection httpCon = null;
            
            // Check if the connection object if of type HttpUrlConnection
            if(con instanceof HttpURLConnection) {
                 httpCon = (HttpURLConnection) con;
            } else {
                return null;
            }
            
            // For redirects
            httpCon.setFollowRedirects(true);
            httpCon.setInstanceFollowRedirects(true);
            
            String contentType = httpCon.getContentType();
             
            int responseCode = httpCon.getResponseCode();
            
            if(responseCode == 200 || responseCode == 302) {
                // content type = null for ssl connections
                if(contentType != null) {
                    // Only if the content-type is that of HTML or PLAIN, we go ahead and fetch the contents
                    if(contentType.contains("text/html") || contentType.contains("text/plain")) {
                        rdr = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));

                        String line = null;
                        content = new StringBuffer();

                        while( (line = rdr.readLine()) != null ) {
                            content.append(line);
                        }

                        rdr.close();
                        
                        return content.toString();
                    }
                }
            }
        } catch(Exception e) {
            try {
                rdr.close();
            } catch(Exception ie) {
                // Do nothing
            }
            
            System.out.println(e);
            return null;
        }

        return null;
    }
    
}
